// 这是用户管理页面的js
// 当页面加载完成时添加事件监听
document.addEventListener('DOMContentLoaded', function() {
    // 监听全局的switchContent函数调用
    window.addEventListener('contentSwitch', function(event) {
        if (event.detail.id === '003') {
            console.log('用户管理内容被切换显示');
            fetchUserList();
			initializeUserManagement(); 
        }
    });

    // 调试输出
    console.log('用户管理模块初始化完成');
});

// 获取用户列表数据
function fetchUserList(page = 1, size = 10) {
    console.log('开始获取用户列表, 页码:', page, '每页条数:', size);
    currentPage = page;
    pageSize = size;

    const params = new URLSearchParams({
        method: 'queryall',
        pageno: page.toString(),
        pagesize: size.toString(),
        id: '123'
    });

    fetch(config.usersip, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
    })
    .then(response => response.json())
    .then(data => {
        console.log('服务器返回的用户数据:', data);
        if (data && data.data) {
            totalUsers = data.total; // 从后端获取总数
            renderUserTable(data.data);
            updateUserPagination(totalUsers, currentPage, pageSize);
        } else {
            console.error('无效的数据格式:', data);
            renderUserTable([]);
            updateUserPagination(0, 1, pageSize);
        }
    })
    .catch(error => {
        console.error('获取用户列表失败:', error);
        renderUserTable([]);
        updateUserPagination(0, 1, pageSize);
    });
}

// 添加日期格式化函数
function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return dateString; // 如果转换失败，返回原字符串
    
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 修改渲染表格函数，添加复选框状态检查
function renderUserTable(users) {
    const userSection = document.getElementById('003');
    const tbody = userSection.querySelector('tbody');
    if (!tbody) {
        console.error('未找到用户表格的tbody元素');
        return;
    }

    tbody.innerHTML = '';
    const startIndex = (currentPage - 1) * pageSize + 1;

    users.forEach((user, index) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td><input type="checkbox" class="row-checkbox"></td>
            <td>${startIndex + index}</td>
            <td>${user.id || ''}</td>
            <td>${user.name || ''}</td>
            <td>${user.phone || ''}<br />${user.email || ''}</td>
            <td>${user.rname || ''}</td>
            <td>${formatDate(user.registrationtime) || ''}</td>
            <td>${formatDate(user.lastlogintime) || ''}</td>
            <td>${user.status === '1' ? '启用' : '禁用'}</td>
            <td>
                <a href="#" onclick="toggleUserStatus(${user.id}, '${user.status}')" class="status-toggle">
                    ${user.status === '1' ? '禁用' : '启用'}
                </a>
            </td>
        `;
        tbody.appendChild(row);
    });

    // 添加行复选框事件监听
    const rowCheckboxes = tbody.querySelectorAll('.row-checkbox');
    const selectAllCheckbox = document.querySelector('thead input[type="checkbox"]');
    
    rowCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const allChecked = Array.from(rowCheckboxes).every(cb => cb.checked);
            const someChecked = Array.from(rowCheckboxes).some(cb => cb.checked);
            selectAllCheckbox.checked = allChecked;
            selectAllCheckbox.indeterminate = someChecked && !allChecked;
        });
    });
}

// 添加用户管理初始化函数
function initializeUserManagement() {
    // 绑定添加用户按钮点击事件
    const addUserBtn = document.getElementById('addUser');
    if (addUserBtn) {
        addUserBtn.addEventListener('click', function() {
            console.log('点击了添加用户按钮');
            showUserModal();
        });
    }

    // 绑定模态框表单提交事件
    const addUserForm = document.getElementById('addUserForm');
    if (addUserForm) {
        addUserForm.addEventListener('submit', handleAddUserSubmit);
    }
	
	// 添加角色选择变化事件监听
	const roleInputs = document.querySelectorAll('input[name="userRole"]');
	roleInputs.forEach(input => {
		input.addEventListener('change', function() {
			const teacherFields = document.getElementById('teacherFields');
			if (this.value === '老师') {
				teacherFields.style.display = 'block';
			} else {
				teacherFields.style.display = 'none';
			}
		});
	});
   // 添加每页显示条数选择事件
	const pageSizeSelect = document.getElementById('userPageSize');
	if (pageSizeSelect) {
		pageSizeSelect.addEventListener('change', function() {
			const newSize = parseInt(this.value);
			fetchUserList(1, newSize); // 切换每页显示条数时返回第一页
		});
	}
	  // 添加页码跳转事件
	    const pageJumpInput = document.querySelector('#003 .page-jump input');
	    if (pageJumpInput) {
	        pageJumpInput.addEventListener('keypress', function(e) {
	            if (e.key === 'Enter') {
	                const pageNum = parseInt(this.value);
	                const totalPages = Math.ceil(totalUsers / pageSize);
	                if (pageNum && pageNum > 0 && pageNum <= totalPages) {
	                    fetchUserList(pageNum, pageSize);
	                } else {
	                    alert('请输入有效的页码！');
	                    this.value = currentPage;
	                }
	            }
	        });
	    }
}

// 显示用户模态框
function showUserModal() {
    const modal = document.getElementById('userModal');
    if (modal) {
        // 重置表单
        const form = document.getElementById('addUserForm');
        if (form) {
            form.reset();
        }
        
        // 确保教师字段初始隐藏
        const teacherFields = document.getElementById('teacherFields');
        if (teacherFields) {
            teacherFields.style.display = 'none';
        }
        
        // 显示模态框
        modal.style.display = 'flex';
        
        // 添加模态框关闭事件（点击外部区域关闭）
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                closeUserModal();
            }
        });
    }
}

// 关闭用户模态框
function closeUserModal() {
    const modal = document.getElementById('userModal');
    if (modal) {
        // 重置表单
        const form = document.getElementById('addUserForm');
        if (form) {
            form.reset();
        }
        
        // 隐藏教师字段
        const teacherFields = document.getElementById('teacherFields');
        if (teacherFields) {
            teacherFields.style.display = 'none';
        }
        
        modal.style.display = 'none';
    }
}

// 处理添加用户表单提交
// 修改处理添加用户表单提交函数
function handleAddUserSubmit(event) {
    event.preventDefault();
    
    // 表单验证
    const userName = document.getElementById('userName').value.trim();
    const userPhone = document.getElementById('userPhone').value.trim();
    const userEmail = document.getElementById('userEmail').value.trim();
    const userPassword = document.getElementById('userPassword').value;
    const userRole = document.querySelector('input[name="userRole"]:checked')?.value;

    // 基本字段验证
    if (!userName || !userPhone || !userEmail || !userPassword || !userRole) {
        alert('请填写所有必填字段！');
        return;
    }

    // 手机号验证
    if (!/^1[3-9]\d{9}$/.test(userPhone)) {
        alert('请输入有效的手机号码！');
        return;
    }

    // 邮箱验证
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userEmail)) {
        alert('请输入有效的邮箱地址！');
        return;
    }

    // 构建请求参数
    const params = new URLSearchParams({
        method: 'add',
        name: userName,
        phone: userPhone,
        email: userEmail,
        password: userPassword,
        role: userRole,
        id: '123'
    });
    
    // 如果是教师角色，验证并添加教师特有信息
    if (userRole === '老师') {
        const direction = document.getElementById('direction').value.trim();
        const workyears = document.getElementById('workyears').value.trim();
        const introduce = document.getElementById('introduce').value.trim();
        
        if (!direction || !workyears || !introduce) {
            alert('请填写完整的教师信息！');
            return;
        }
        
        params.append('direction', direction);
        params.append('workyears', workyears);
        params.append('introduce', introduce);
    }

    // 发送请求
    fetch(config.usersip, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('用户添加成功！');
            closeUserModal();
            fetchUserList(currentPage, pageSize); // 刷新当前页面
        } else {
            alert(data.msg || '添加用户失败，请重试！');
        }
    })
    .catch(error => {
        console.error('添加用户失败:', error);
        alert('添加用户失败，请稍后重试！');
    });
}


// 分页相关变量
let currentPage = 1;
let pageSize = 10;
let totalUsers = 0;

// 修改获取用户列表函数，添加分页参数
// 获取用户列表数据
function fetchUserList(page = 1, size = 10) {
    console.log('开始获取用户列表, 页码:', page, '每页条数:', size);
    currentPage = page;
    pageSize = size;

    const params = new URLSearchParams({
        method: 'queryall',
        pageno: page.toString(),
        pagesize: size.toString(),
        id: '123'
    });

    fetch(config.usersip, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
    })
    .then(response => response.json())
    .then(data => {
        console.log('服务器返回的用户数据:', data);
        if (data && data.data) {
            totalUsers = data.total; // 从后端获取总数
            renderUserTable(data.data);
            updateUserPagination(totalUsers, currentPage, pageSize);
            updateTotalCount(totalUsers);
        } else {
            console.error('无效的数据格式:', data);
            renderUserTable([]);
            updateUserPagination(0, 1, pageSize);
            updateTotalCount(0);
        }
    })
    .catch(error => {
        console.error('获取用户列表失败:', error);
        renderUserTable([]);
        updateUserPagination(0, 1, pageSize);
        updateTotalCount(0);
    });
}
// 更新分页UI的函数
// 更新分页UI
function updatePagination(total, currentPage, pageSize) {
    const totalPages = Math.ceil(total / pageSize);
    const paginationDiv = document.querySelector('[id="003"] .pagination');
    paginationDiv.innerHTML = '';

    // 上一页
    const prevButton = document.createElement('a');
    prevButton.href = '#';
    prevButton.className = `prev${currentPage === 1 ? ' disabled' : ''}`;
    prevButton.textContent = '上一页';
    prevButton.addEventListener('click', (e) => {
        e.preventDefault();
        if (currentPage > 1) {
            fetchUserList(currentPage - 1, pageSize);
        }
    });
    paginationDiv.appendChild(prevButton);

    // 页码
    for (let i = 1; i <= totalPages; i++) {
        const pageButton = document.createElement('a');
        pageButton.href = '#';
        pageButton.className = `page${i === currentPage ? ' active' : ''}`;
        pageButton.textContent = i;
        pageButton.addEventListener('click', (e) => {
            e.preventDefault();
            fetchUserList(i, pageSize);
        });
        paginationDiv.appendChild(pageButton);
    }

    // 下一页
    const nextButton = document.createElement('a');
    nextButton.href = '#';
    nextButton.className = `next${currentPage === totalPages ? ' disabled' : ''}`;
    nextButton.textContent = '下一页';
    nextButton.addEventListener('click', (e) => {
        e.preventDefault();
        if (currentPage < totalPages) {
            fetchUserList(currentPage + 1, pageSize);
        }
    });
    paginationDiv.appendChild(nextButton);
}
// 更新分页UI
function updateUserPagination(total, currentPage, pageSize) {
    const totalPages = Math.ceil(total / pageSize);
    const paginationDiv = document.querySelector('[id="003"] .pagination');
    if (!paginationDiv) return;
    
    paginationDiv.innerHTML = '';

    // 上一页按钮
    const prevLink = createPageButton('上一页', 'prev', currentPage === 1, () => {
        if (currentPage > 1) {
            fetchUserList(currentPage - 1, pageSize);
        }
    });
    paginationDiv.appendChild(prevLink);

    // 生成页码按钮
    const pageNumbers = generatePageNumbers(currentPage, totalPages);
    pageNumbers.forEach(num => {
        if (num === '...') {
            const ellipsis = document.createElement('span');
            ellipsis.className = 'ellipsis';
            ellipsis.textContent = '...';
            paginationDiv.appendChild(ellipsis);
        } else if (!isNaN(num)) {
            const pageLink = createPageButton(
                num.toString(), 
                'page', 
                false, 
                () => fetchUserList(num, pageSize)
            );
            // 当前页添加active类
            if (num === currentPage) {
                pageLink.classList.add('active');
            }
            paginationDiv.appendChild(pageLink);
        }
    });

    // 下一页按钮
    const nextLink = createPageButton('下一页', 'next', currentPage === totalPages, () => {
        if (currentPage < totalPages) {
            fetchUserList(currentPage + 1, pageSize);
        }
    });
    paginationDiv.appendChild(nextLink);
}
// 生成页码数组
function generatePageNumbers(current, total) {
    if (total <= 7) {
        return Array.from({length: total}, (_, i) => i + 1);
    }

    if (current <= 3) {
        return [1, 2, 3, 4, '...', total];
    }

    if (current >= total - 2) {
        return [1, '...', total - 3, total - 2, total - 1, total];
    }

    return [1, '...', current - 1, current, current + 1, '...', total];
}
// 更新分页信息（总条数和页码输入框）
// function updatePaginationInfo(total, currentPage, totalPages) {
//     // 更新总条数显示
//     const totalCountSpan = document.querySelector('[id="003"] .total-count span');
//     if (totalCountSpan) {
//         totalCountSpan.textContent = total;
//     }

//     // 更新页码输入框
//     const pageJumpInput = document.querySelector('[id="003"] .page-jump input');
//     if (pageJumpInput) {
//         pageJumpInput.value = currentPage;
//         pageJumpInput.max = totalPages;
//     }
// }

// 更新总条数显示
// function updateTotalCount(total) {
//     const totalCountSpan = document.querySelector('[id="003"] .total-count span');
//     if (totalCountSpan) {
//         totalCountSpan.textContent = total;
//     }
// }
// 创建分页按钮
function createPageButton(text, className, isDisabled, onClick) {
    const button = document.createElement('a');
    button.href = '#';
    button.className = className + (isDisabled ? ' disabled' : '');
    button.textContent = text;
    
    if (!isDisabled) {
        button.addEventListener('click', (e) => {
            e.preventDefault();
            onClick();
            
            // 移除所有页码按钮的active类
            document.querySelectorAll('.pagination .page').forEach(btn => {
                btn.classList.remove('active');
            });
            
            // 如果是页码按钮，添加active类
            if (className === 'page') {
                button.classList.add('active');
            }
        });
    }
    return button;
}

// 修改初始化函数，删除重复的roleInputs声明
function initializeUserManagement() {
    // 绑定添加用户按钮点击事件
    const addUserBtn = document.getElementById('addUser');
    if (addUserBtn) {
        addUserBtn.addEventListener('click', function() {
            console.log('点击了添加用户按钮');
            showUserModal();
        });
    }

    // 绑定模态框表单提交事件
    const addUserForm = document.getElementById('addUserForm');
    if (addUserForm) {
        addUserForm.addEventListener('submit', handleAddUserSubmit);
    }
    
    // 添加角色选择变化事件监听（保留一处roleInputs声明）
    const roleInputs = document.querySelectorAll('input[name="userRole"]');
    roleInputs.forEach(input => {
        input.addEventListener('change', function() {
            const teacherFields = document.getElementById('teacherFields');
            if (teacherFields) {
                teacherFields.style.display = this.value === '老师' ? 'block' : 'none';
                
                // 如果切换到非教师角色，清空教师字段
                if (this.value !== '老师') {
                    const teacherInputs = teacherFields.querySelectorAll('input, textarea');
                    teacherInputs.forEach(input => input.value = '');
                }
            }
        });
    });

    // 添加每页显示条数选择事件
    const pageSizeSelect = document.getElementById('userPageSize');
    if (pageSizeSelect) {
        pageSizeSelect.addEventListener('change', function() {
            pageSize = parseInt(this.value);
            fetchUserList(1, pageSize); // 切换每页显示条数时返回第一页
        });
    }

    // 添加全选复选框事件监听
    const selectAllCheckbox = document.querySelector('thead input[type="checkbox"]');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('tbody input[type="checkbox"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
    }

    // 添加搜索功能
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        let searchTimeout;
        searchInput.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                const searchTerm = this.value.trim();
                if (searchTerm) {
                    searchUsers(searchTerm);
                } else {
                    fetchUserList(); // 如果搜索框为空，显示所有用户
                }
            }, 500); // 500ms防抖
        });
    }
}

// 添加搜索用户函数
function searchUsers(searchTerm) {
    console.log('搜索用户:', searchTerm);
    const params = new URLSearchParams({
        method: 'search',
        keyword: searchTerm,
        id: '123'
    });

    fetch(config.usersip, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
    })
    .then(response => response.json())
    .then(data => {
        console.log('搜索结果:', data);
        if (data && data.data) {
            renderUserTable(data.data);
            updateUserPagination(data.total || data.data.length, 1, pageSize);
            updateTotalCount(data.total || data.data.length);
        } else {
            console.error('搜索返回的数据格式无效:', data);
            renderUserTable([]);
            updateUserPagination(0, 1, pageSize);
            updateTotalCount(0);
        }
    })
    .catch(error => {
        console.error('搜索用户失败:', error);
        renderUserTable([]);
        updateUserPagination(0, 1, pageSize);
        updateTotalCount(0);
    });
}

// 确保closeUserModal函数在全局作用域可用
window.closeUserModal = closeUserModal;